//
//  AppDelegate.m
//  CarUser
//
//  Created by 王森林 on 2018/11/29.
//  Copyright © 2018年 王森林. All rights reserved.
//

#import "AppDelegate.h"
#import "BaseTabBarViewController.h"
#import "FirstEnterAppViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import <WXApi.h>
@interface AppDelegate ()<WXApiDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    if (@available(iOS 11.0, *)) {
        [UIScrollView appearance].contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        [UITableView appearance].estimatedSectionFooterHeight = 0;
        [UITableView appearance].estimatedSectionHeaderHeight = 0;
    } else {
        
    }
    [SVProgressHUD setMinimumDismissTimeInterval:2];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setMinimumSize:CGSizeMake(70, 0)];
    [SVProgressHUD setFont:[UIFont systemFontOfSize:14]];
    [SVProgressHUD setInfoImage:IMG(@"")];
    
    
    
    [WXApi registerApp:@"wx80e2028d0aa70fb8"];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *oldVersion = [[NSUserDefaults standardUserDefaults] objectForKey: @"caruser_version"];
    // 第一次启动
    if (oldVersion == nil) {
        FirstEnterAppViewController *vc = [[FirstEnterAppViewController alloc] init];
        self.window.rootViewController = vc;
    }else{
        // 新版本
        NSString *oldv = [NSString stringWithFormat:@"%@",oldVersion];
        if ([oldv compare:appVersion options:NSNumericSearch] == NSOrderedAscending) {
            FirstEnterAppViewController *vc = [[FirstEnterAppViewController alloc] init];
            self.window.rootViewController = vc;
        }else {
            BaseTabBarViewController *root = [[BaseTabBarViewController alloc] init];
            self.window.rootViewController = root;
        }
    }
    
//    BaseTabBarViewController *root = [[BaseTabBarViewController alloc] init];
//    self.window.rootViewController =  root;
    

    
    [self.window makeKeyAndVisible];
    
    return YES;
}
//回调
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    if([url.description hasPrefix:@"wx"]){
        return  [WXApi handleOpenURL:url delegate:self];
    }
    return  [WXApi handleOpenURL:url delegate:self];
}


- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    if([url.description hasPrefix:@"wx"]){
        return  [WXApi handleOpenURL:url delegate:self];
    }
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            NSString *result = resultDic[@"result"];
            BOOL isok = NO;
            if (result.length>0) {
                id resultDic = [result mj_JSONObject];
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    if ([resultDic[@"alipay_trade_app_pay_response"][@"msg"] isEqualToString:@"Success"]) {
                        isok = YES;
                    }
                }
            }
            if ([resultDic[@"resultStatus"] integerValue] == 9000 && isok) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showInfoWithStatus:@"付款成功"];
                    
                     [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_PaySuccess object:nil];
                    
//                    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/*延迟执行时间*/ * NSEC_PER_SEC));
//
//                    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
//                        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_PaySuccess object:nil];
//                    });
                    
                   
                    //                [SVProgressHUD dismissWithDelay:10];
                });
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showInfoWithStatus:@"付款失败"];
                    //                [SVProgressHUD dismissWithDelay:10];
                });
            }
        }];
    }
   return  [WXApi handleOpenURL:url delegate:self];;
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    
    if([url.description hasPrefix:@"wx"]){
        return  [WXApi handleOpenURL:url delegate:self];
    }
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            NSString *result = resultDic[@"result"];
            BOOL isok = NO;
            if (result.length>0) {
                id resultDic = [result mj_JSONObject];
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    if ([resultDic[@"alipay_trade_app_pay_response"][@"msg"] isEqualToString:@"Success"]) {
                        isok = YES;
                    }
                }
            }
            if ([resultDic[@"resultStatus"] integerValue] == 9000 && isok) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showInfoWithStatus:@"付款成功"];
                    [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_PaySuccess object:nil];
                    //                [SVProgressHUD dismissWithDelay:10];
                });
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showInfoWithStatus:@"付款失败"];
                    //                [SVProgressHUD dismissWithDelay:10];
                });
            }
        }];
    }
    return YES;
}

//微信回调
-(void)onResp:(BaseResp *)resp
{
    Class class = [resp class];
    Class sendmessage = [SendMessageToWXResp class];
    Class loginClass = [SendAuthResp class];
    Class payClass = [PayResp class];
    if(class == loginClass){
        SendAuthResp *loginInfo = (SendAuthResp *)resp;
//        [[NSNotificationCenter defaultCenter]postNotificationName:BX_NotificationCenterName_WeixinLogin object:loginInfo userInfo:nil];
    }else if(class == payClass){
        PayResp *payInfo = (PayResp *)resp;
        
        if (payInfo.errCode == 0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showSuccessWithStatus:@"支付成功"];
            });
            [SVProgressHUD showInfoWithStatus:@"付款成功"];
            [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_PaySuccess object:nil];
        }else{
            if (payInfo.errCode == -2) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showErrorWithStatus:@"用户取消支付"];
                });
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showErrorWithStatus:payInfo.errStr];
                });
            }
        
        }
        
        
        
//        [[NSNotificationCenter defaultCenter] postNotificationName:BX_NotificationCenterName_WeixinPayBack object:payInfo userInfo:nil];
    }else if(class == sendmessage){
//        [[NSNotificationCenter defaultCenter] postNotificationName:BX_NotificationCenterName_WeixinShareCallBack object:nil userInfo:nil];
    }
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
